package com.feicheng.common.mqtt;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttOutboundChannel {

    @Value("${spring.mqtt.username}")
    protected String username;

    @Value("${spring.mqtt.password}")
    protected String password;

    @Value("${spring.mqtt.url}")
    protected String url;

    private MqttAsyncClient client;

    @Value("${mqtt.enable}")
    Boolean mqttEnabled;

    @PostConstruct
    public void init() {
        if (mqttEnabled) {
            connect();
        }
    }

    public Boolean getMqttClientStu() {

        if (null == this.client) {
            return false;
        }

        return this.client.isConnected();
    }

    private void connect() {
        MqttConnectOptions option = new MqttConnectOptions();
        option.setCleanSession(true);
        option.setUserName(username);
        option.setPassword(password.toCharArray());
        option.setConnectionTimeout(60);
        option.setKeepAliveInterval(20);
        option.setAutomaticReconnect(true);

        try {
            client = new MqttAsyncClient(url, "server-outbound", new MemoryPersistence());

            client.connect(option, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken iMqttToken) {
                    log.info("发送通道MQTT连接成功");
                }

                @Override
                public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
                    log.error("发送通道MQTT连接失败", throwable);
                }
            });
        } catch (MqttException e) {
            log.error("发送通道连接MQTT失败", e);

            while (!getMqttClientStu()) {
                try {
                    Thread.sleep(100000L);
                } catch (Exception e1) {

                }
                connect();
            }

        }

    }

    public void sendMessage(String topic, String message) {
        this.publish(1, false, topic, message);
    }

    public void publish(int qos, boolean retained, String topic, String message) {
        MqttMessage msg = new MqttMessage();
        msg.setQos(qos);
        msg.setRetained(retained);
        msg.setPayload(message.getBytes());

        try {
            client.publish(topic, msg, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken iMqttToken) {
                    log.info("发送成功");
                }

                @Override
                public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
                    log.error("发送失败", throwable);
                }
            });
        } catch (MqttException e) {
            log.error("发送消息失败：", e);
        }
    }

    public void disConnect() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            log.error("", e);
        }
    }
}
